package com.example.controller;

import cn.hutool.core.date.DateUtil;
import com.example.common.util.R;
import com.example.config.shiro.JwtUtil;
import com.example.db.form.CheckinForm;
import com.example.service.CheckinService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.Objects;

/**
 * @Author: AlbertHPW
 * @Date: 2025/6/22 19:15
 */
@RequestMapping("/checkin")
@RestController
@Api(tags = "签到模块Web接口")
@Slf4j
public class CheckinController {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private CheckinService checkinService;

    @GetMapping("/validCanCheckIn")
    @ApiOperation("查看用户今天是否可以签到")
    public R validCanCheckIn(@RequestHeader("token") String token) {
        int userId = jwtUtil.getUserId(token);
        String result = checkinService.validCanCheckIn(userId, DateUtil.today());
        return R.ok(result);
    }

    @PostMapping("/checkin")
    @ApiOperation("签到")
    public R checkin(@Valid CheckinForm form, @RequestParam("photo") MultipartFile file, @RequestHeader("token") String token) {
        if (file == null) {
            return R.error("没有上传文件");
        }
        int userId = jwtUtil.getUserId(token);
        // 从文件对象中获取原始文件名，如果文件对象为null，则抛出NullPointerException
        String fileName = Objects.requireNonNull(file.getOriginalFilename()).toLowerCase();

        if(!fileName.endsWith(".jpg")){
            return R.error("必须提交JPG格式图片");
        }
        return  null;
    }

}
